const log4js = require('./logUtils');
const logger = log4js.getLogger('util');
const http = require('http');
const https = require('https');

const TAG = "[HTTP]";
let httpUtils = {
    get(url, param) {
        return new Promise(function (resolve, reject) {
            if (!url) {
                reject("url不能为空");
            } else {
                if (!param) {
                    param = '';
                }
                // 去掉最后的问号
                if (url.lastIndexOf('?') === url.length - 1) {
                    url = url.substring(0, url.length - 1);
                }
                // 去掉前面的问号
                if (param.indexOf('?') === 0) {
                    param = param.substring(1, param.length);
                }
                // 根据协议选择使用哪个模块
                let httpProtocol;
                if (url.indexOf('https://') === 0) {
                    httpProtocol = https;
                } else {
                    httpProtocol = http;
                }
                let mergeUrl;
                // 如果url包含了?，就用&拼接，否则用?
                if (url.indexOf('?') > 0) {
                    mergeUrl = url + '&' + param;
                } else {
                    mergeUrl = url + '?' + param;
                }
                httpProtocol.get(mergeUrl, (res) => {
                    let html = "";
                    res.on("data", (data) => {
                        html += data;
                    });
                    res.on("end", () => {
                        logger.info(TAG, "请求",url, "响应",html);
                        resolve(JSON.parse(html));
                    });
                }).on('error', (e) => {
                    logger.trace('请检查http是否启动， error=', e, 'url=', url, 'param=', param);
                    reject(e);
                });
            }
        });

    }
};

module.exports = httpUtils;
